import React, { cloneElement, createRef, ReactElement, useMemo } from "react";
import { Button, Form, FormInstance, Modal, ModalProps } from "antd";
import styles from "./index.module.css";
import { QueryClientProvider } from "@tanstack/react-query";
import { queryClient } from "../../utils/queryClient";

type DialogCallback = (
  values: Record<string, any>,
  hide: () => void,
  core?: FormInstance | undefined
) => void;

type Props = {
  content?: ReactElement;
  onOk?: DialogCallback;
  onCancel?: DialogCallback;
  hideConfirm?: boolean
} & Omit<ModalProps, "onOk" | "onCancel">;

const Dialog = (props: Props) => {
  const { content, onOk, onCancel, hideConfirm, ...modalProps } = props;
  let ref = createRef<FormInstance>();

  const onCallbackMiddle = async (fn?: DialogCallback, hide?: any) => {
    const formValues = ref.current ? ref.current.getFieldsValue(true) : {};
    await ref.current?.validateFields?.();
    fn?.(formValues, hide || (() => {}), ref.current);
  };
  const core = content
    ? cloneElement(content, {
        ref,
      })
    : content;
  if (content?.props?.getFormRef) {
    content?.props?.getFormRef?.(ref);
  }

  const node = (
    <QueryClientProvider client={queryClient}>
      <div className="flex flex-col">
        <div className="flex-1">{core}</div>
        <div className="mt-[10px] flex items-center justify-end">
          <Button
            type="default"
            onClick={() => {
              onCallbackMiddle(onCancel, instance?.destroy).then();
              instance.destroy();
            }}
          >
            取消
          </Button>
          {!hideConfirm && <Button
            type="primary"
            className="ml-[10px]"
            onClick={() => {
              onCallbackMiddle(onOk, instance?.destroy).then();
            }}
          >
            确认
          </Button>}
        </div>
      </div>
    </QueryClientProvider>
  );

  const instance = Modal.confirm({
    content: node,
    className: styles.dialogContainer,
    icon: null,
    footer: null,
    ...modalProps,
  });
};

export default Dialog;
